package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;


@Service("attrService")
@Transactional(rollbackFor = Exception.class)
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity); //保存规格参数
        if (attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode())) {
            Long attrId = attrEntity.getAttrId();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrId);
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            Integer count = attrAttrgroupRelationDao.selectCount(
                    new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity
                        , new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

        return R.ok();

    }

    @Override
    public R queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        LambdaQueryWrapper<AttrEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttrEntity::getAttrType, "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {
            queryWrapper.eq(AttrEntity::getCatelogId, catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVoList = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
                if (!org.springframework.util.StringUtils.isEmpty(attrAttrgroupRelationEntity.getAttrGroupId())) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao
                            .selectOne(new LambdaQueryWrapper<AttrGroupEntity>()
                                    .eq(AttrGroupEntity::getAttrGroupId, attrAttrgroupRelationEntity.getAttrGroupId()));
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (!org.springframework.util.StringUtils.isEmpty(categoryEntity)) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        })).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVoList);
        return R.ok().put("page", pageUtils);
    }

    @Override
    public R getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId())); // 关联表查询
        List<Long> catelogPaths = new ArrayList<>();
        Long catelogId = attrEntity.getCatelogId();
        this.getCatelogPaths(catelogPaths, catelogId);
        Collections.reverse(catelogPaths);
        if (!org.springframework.util.StringUtils.isEmpty(relationEntity)
                && !org.springframework.util.StringUtils.isEmpty(relationEntity.getAttrGroupId())) {
            Long attrGroupId = relationEntity.getAttrGroupId();
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
            attrRespVo.setAttrGroupId(attrGroupId); // 装入分组id
            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName()); //装入分组名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrGroupEntity.getCatelogId());
            if (org.springframework.util.StringUtils.isEmpty(categoryEntity))
                throw new RRException("分组中未关联分类名:(", 20001);
            attrRespVo.setCatelogName(categoryEntity.getName()); // 设置分类名
        }
        attrRespVo.setCatelogPath((Long[]) catelogPaths.toArray(new Long[catelogPaths.size()])); // 将父id装入集合
//        if (org.springframework.util.StringUtils.isEmpty(attrGroupEntity))
//            throw new RRException("属性关联分组中没有关联改分组:(", 20001);
        return R.ok().put("attr", attrRespVo);
    }

    @Override
    public R getGroups(Map<String, Object> params, Long catelogId) {
        LambdaQueryWrapper<AttrGroupEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttrGroupEntity::getCatelogId, catelogId)
                .select(AttrGroupEntity::getAttrGroupId, AttrGroupEntity::getAttrGroupName);
        IPage<AttrGroupEntity> pages = attrGroupDao.selectPage(new Query<AttrGroupEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(pages);
        return R.ok().put("page", pageUtils);
    }

    @Override
    public R attrRelation(String attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId));
        Optional<List<AttrAttrgroupRelationEntity>> relationEntitiesList = Optional.ofNullable(relationEntities);
        boolean present = relationEntitiesList.isPresent();
        Objects.requireNonNull(relationEntities, "该分组尚未关联属性:(");
        List<Long> attrIds = relationEntities.stream().map(relationEntity -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return R.ok().put("data", (List<AttrEntity>) attrEntities);
    }

    private void getCatelogPaths(List<Long> catelogPaths, Long catelogId) {
        catelogPaths.add(catelogId);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            this.getCatelogPaths(catelogPaths, categoryEntity.getParentCid());
        }
    }

    @Override
    public R deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = Arrays.asList(vos).stream().map((vo) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRealations(attrgroupRelationEntityList); // 批量删除
        return R.ok();
    }

    @Override
    public R getNoAttrRelation(Map<String, Object> params, String attrgroupId) {
        //当前分组只能怪关联自己所属分类所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Objects.requireNonNull(20001, "没有当前分组:(");
        Long catelogId = attrGroupEntity.getCatelogId();
        LambdaQueryWrapper<AttrEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new LambdaQueryWrapper<AttrGroupEntity>()
                .eq(AttrGroupEntity::getCatelogId, catelogId));
        //当前分组
        List<Long> attrGroups = attrGroupEntities.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(attrGroups)) {
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao
                    .selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                            .in(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroups));

            List<Long> attrIds = relationEntities.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            queryWrapper = new LambdaQueryWrapper<AttrEntity>()
                    .eq(AttrEntity::getCatelogId, catelogId)
                    .eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode());
            if (CollectionUtils.isNotEmpty(attrIds)) {
                queryWrapper.notIn(AttrEntity::getAttrId, attrIds);
            }
            String key = (String) params.get("key");
            if (!StringUtils.isEmpty(key)) {  // 如果key不为空要进行其他条件匹配查询
                //方法一拼接and
                //   queryWrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
                //方法二拼接and
                queryWrapper.and((wrapper) -> {
                    wrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
                });
            }
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return R.ok().put("page", new PageUtils(page));
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_BASE_TYPE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            Integer count = attrAttrgroupRelationDao.selectCount(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity
                        , new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }
}